package com.bt.lms.ui.action.divide.plan;

import com.alibaba.fastjson.JSON;
import com.bt.lms.constants.ClassBizTypeConstant;
import com.bt.lms.constants.CourseBizTypeConstant;
import com.bt.lms.entity.ClassInfo;
import com.bt.lms.entity.CourseInfo;
import com.bt.lms.network.msg.RespMsg;
import com.bt.lms.ui.action.divide.plan.vo.DivideVo;
import com.bt.lms.constants.BOConstant;
import com.bt.lms.network.msg.ReqMsg;
import com.bt.lms.network.msg.packet.ReqMsgPacket;
import com.bt.lms.ui.page.common.action.pagerecord.SeparateClassLabAction;
import com.bt.lms.ui.page.classes.ManualShift;
import com.bt.lms.ui.page.classes.PreviewShiftResult;
import com.bt.lms.utils.Convert;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import org.apache.commons.beanutils.BeanUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.Socket;

/**
 * 手动分班预览分班结果按钮事件
 */
public class PrePageManualShiftBtnAction implements EventHandler {

    private ManualShift manualShift; //手动分班页面

    //维护界面
    public PrePageManualShiftBtnAction(ManualShift manualShift) {
        this.manualShift = manualShift;
    }

    @Override
    public void handle(Event event) {

        //1.获取用户输入，返回VO：里面承载着用户的输入
        DivideVo divideVo = getInParams();
        //2.验证用户输入，inP:VO outP:消息
        String validateMsg = validateInParam(divideVo);
        //3.组包（根据自定义的网络消息协议），inP:VO outP:消息
        byte[] bytes = null;
        if (null == validateMsg) {

            //验证通过，组包
            bytes = handle2ReqMsg(divideVo);

        } else {
            //提示，程序终止
            return;
        }
        //4.组网（根据咱们自定义的网络连接交互规范来定义）inP:服务器的信息（ip,port....）
        Socket socket = getNet();
        //5.发送消息，inP:消息 ouP:是否发送成熟
        boolean flag = send(socket, bytes);

        PreviewShiftResult previewShiftResult = new PreviewShiftResult();
        Pane pane = SeparateClassLabAction.pageSkipInfo.getPane();
        Integer index = SeparateClassLabAction.pageSkipInfo.getIndex();
        pane.getChildren().set(index, previewShiftResult);
    }

    /**
     * 发送信息
     * 1.将消息转为字节流
     * 2.发送
     *
     * @param socket 发送的socket
     * @param bytes 要发送的消息
     * @return
     */
    private boolean send(Socket socket, byte[] bytes) {
        try {
            //发送消息
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(bytes); //写
            outputStream.flush();//冲刷

            //接收回应信息
            InputStream in = socket.getInputStream();
            byte[] buf = new byte[1024];
            in.read(buf); //读
            RespMsg respMsg = RespMsg.toRespMsg(buf);
            String data = respMsg.getData();

        } catch (IOException e) {
//            throw new RuntimeException(e);
        }

        return true;
    }


    /**
     * 获取网络
     *
     * @return socket
     */
    private Socket getNet() {
        String serverIp = "127.0.0.1";
        int serverPort = 8888;
        Socket socket = null;

        try {
            socket = new Socket(serverIp, serverPort);
        } catch (IOException e) {
//            throw new RuntimeException(e);
            return null;
        }

        return socket;
    }

    /**
     * 将用户输入的信息处理成我们规定的请求信息
     *
     * @param divideVo 用户输入
     * @return 请求消息
     */
    private byte[] handle2ReqMsg(DivideVo divideVo) {
        //消息
        ReqMsg reqMsg = new ReqMsg();

        //课程信息
        ClassInfo classInfo = new ClassInfo();

        //业务类型
        reqMsg.setBizType(ClassBizTypeConstant.DIVIDE_PLAN_RANDOM_AVERAGE);

        //vo转entity(目标，源)
        try {
            BeanUtils.copyProperties(classInfo, divideVo);

            String classStr = JSON.toJSONString(divideVo);
            //数据带走
            reqMsg.setData(classStr);

        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        byte[] bytes = reqMsg.toBytes();

        return bytes;
    }

    /**
     * 验证用户的输入是否符合条件
     *
     * @param divideVo 用户的输入信息
     * @return 验证消息
     */
    private String validateInParam(DivideVo divideVo) {
        String msg = ""; //所有提示信息
        //分班数
        String shiftsNumber = divideVo.getShiftsNumber();
        String numberBlankMsg = "分班数必须填写！\r\n";
        String numberLengthMsg = "分班数必须大于1且小于350！\r\n";
        String numberFormat = "分班数必须填写数字\r\n";
        if ("".equals(shiftsNumber)) {
            msg += numberBlankMsg;
        } else {
            try {
                int i = Integer.parseInt(shiftsNumber);
                if (i > 350 || i < 1) {
                    msg += numberLengthMsg;
                }
            } catch (NumberFormatException e) {
                msg += numberFormat;
            }
        }

        //班ID
        String classID = divideVo.getClassID();
        String iDBlankMsg = "班级ID必须填写！\n";
        String iDLengthMsg = "班级ID长度在18位以下，包含18！\n";
        if ("".equals(classID)) {
            msg += iDBlankMsg;
        } else {
            if (classID.length() > 18) {
                msg += iDLengthMsg;
            }
        }

        //班级名称
        String className = divideVo.getName();
        String nameBlankMsg = "班级名称必须填写！\n";
        String nameLengthMsg = "班级名称长度在18位以下，包含18！\n";
        if ("".equals(className)) {
            msg += nameBlankMsg;
        } else {
            if (className.length() > 18) {
                msg += nameLengthMsg;
            }
        }
        //手动选择人员人数
        Integer handStuNo = divideVo.getStuNo();
        String stuNoBlankMsg = "请选择学员人数！\n";
        String stuNoLengthMsg = "学员人数必须大于1且小于350！\n";
        if (handStuNo == null) {
            msg += stuNoBlankMsg;
        } else {
            if (handStuNo > 350) {
                msg += stuNoLengthMsg;
            }
        }
        //字符串转null
        if (msg.equals("")) {
            msg = null;
        }

        if (!(msg == null)) {
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setContentText(msg);
            alert.show();
        }

        return msg;
    }

    /**
     * 获取用户输入
     *
     * @return 输入的信息
     */
    private DivideVo getInParams() {
        DivideVo divideVo = new DivideVo();
        //填写分班数
        TextField writeTF = (TextField) manualShift.lookup("#writeTF");
        String divide = writeTF.getText().trim();
        divideVo.setShiftsNumber(divide);
        //填写班ID
        TextField iDTF = (TextField) manualShift.lookup("#iDTF");
        String idText = iDTF.getText().trim();
        divideVo.setClassID(idText);
        //填写班级名称
        TextField nameTF = (TextField) manualShift.lookup("#nameTF");
        String className = nameTF.getText().trim();
        divideVo.setName(className);
        //选择学员人数
        TextField handStuNoTF = (TextField) manualShift.lookup("#handStuNoTF");
        String text = handStuNoTF.getText().trim();
        Integer integer = null;
        try {
            integer = Integer.valueOf(text);
        } catch (NumberFormatException e) {
//            throw new RuntimeException(e);

        }
        divideVo.setStuNo(integer);

        return divideVo;
    }

    public ManualShift getPageManualShift() {
        return manualShift;
    }

    public void setPageManualShift(ManualShift manualShift) {
        this.manualShift = manualShift;
    }
}
